﻿#include <cstdio>
#include <string>
#include <vector>
#include <map>
#include <thread>
#include <iostream>

#include "timer.h"
#include "logs.h"

int cancel_timer_id = 0;
int count_timer_id = 0;
std::mutex mutex;

void hang_up(int id, size_t data)
{
	std::lock_guard<std::mutex> lock(mutex);
	if (id != cancel_timer_id) {
		plogf(logs::info, "hang up has been cancel");
		return;
	}
	cancel_timer_id = 0;
	plogf(logs::info, "hang up");
}

static int count = 0;
void count_time(int id, size_t data)
{
	std::lock_guard<std::mutex> lock(mutex);
	if (id != count_timer_id) {
		plogf(logs::info, "count has been cancel");
		return;
	}
	plogf(logs::info, "count time %d", count++);
}

void signal(int value, Timer &timer)
{
	std::lock_guard<std::mutex> lock(mutex);
	if (value == 1) {
		if (count_timer_id != 0) {
			timer.cancel(count_timer_id);
		}
		if (cancel_timer_id != 0) {
			timer.cancel(cancel_timer_id);
		}
		cancel_timer_id = timer.schedule(hang_up, 1000, 0, false);
	} else if (value == 2) {
		if (count_timer_id != 0) {
			timer.cancel(count_timer_id);
		}
		if (cancel_timer_id != 0) {
			timer.cancel(cancel_timer_id);
		}
		count_timer_id = timer.schedule(count_time, 1000, 0, true);
	}
}

int main()
{
	plogf(logs::info, "start");
	plogf(logs::info, "start");
	plogf(logs::info, "start");
	plogf(logs::info, "start");
	Timer timer;
	logs::glog.hexdump((char*)&timer, 200);
	signal(1, timer);
	plogf(logs::info, "hang up after 1 second");
	std::this_thread::sleep_for(std::chrono::milliseconds(500));
	signal(1, timer);
	plogf(logs::info, "hang up after 1 second");
	std::this_thread::sleep_for(std::chrono::milliseconds(1500));
	signal(1, timer);
	plogf(logs::info, "hang up after 1 second");
	std::this_thread::sleep_for(std::chrono::milliseconds(1500));
	signal(2, timer);
	plogf(logs::info, "count after 1 second");
	std::this_thread::sleep_for(std::chrono::milliseconds(2500));
	signal(1, timer);
	plogf(logs::info, "hang up after 1 second");
	std::this_thread::sleep_for(std::chrono::milliseconds(1500));

	std::this_thread::sleep_for(std::chrono::seconds(10));
	plogf(logs::info, "hello world");
	return 0;
}

